// 出库单状态定义
export const OUTBOUND_STATUS = {
  CANCELLED: 0,      // 已取消
  WAITING_PICKING: 1, // 待拣货
  WAITING_SHIPPING: 2, // 待发货
  COMPLETED: 3       // 已完成
}

// 出库单状态显示文本
export const OUTBOUND_STATUS_TEXT = {
  [OUTBOUND_STATUS.CANCELLED]: '已取消',
  [OUTBOUND_STATUS.WAITING_PICKING]: '待拣货',
  [OUTBOUND_STATUS.WAITING_SHIPPING]: '待发货',
  [OUTBOUND_STATUS.COMPLETED]: '已完成'
}

// 出库单状态标签类型
export const OUTBOUND_STATUS_TAG_TYPE = {
  [OUTBOUND_STATUS.CANCELLED]: 'error',
  [OUTBOUND_STATUS.WAITING_PICKING]: 'warning',
  [OUTBOUND_STATUS.WAITING_SHIPPING]: 'processing',
  [OUTBOUND_STATUS.COMPLETED]: 'success'
}

// 物流方式文本
export const SHIPPING_METHOD_TEXT = {
  sf: '顺丰快递',
  zt: '中通快递',
  yd: '韵达快递',
  ems: 'EMS',
  jd: '京东物流',
  self: '自送'
}

// 格式化日期
export function formatDate(date) {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  const hour = d.getHours().toString().padStart(2, '0')
  const minute = d.getMinutes().toString().padStart(2, '0')
  return `${year}-${month}-${day} ${hour}:${minute}`
}

// 出库单操作权限检查
export function checkOutboundPermission(outbound, action, userRole) {
  if (!outbound) return false

  const { status } = outbound
  
  // 基于角色和状态的权限矩阵
  const permissionMatrix = {
    manager: {
      approve: status === OUTBOUND_STATUS.WAITING_PICKING,
      cancel: [OUTBOUND_STATUS.WAITING_PICKING, OUTBOUND_STATUS.WAITING_SHIPPING].includes(status),
      view: true
    },
    warehouse: {
      pick: status === OUTBOUND_STATUS.WAITING_PICKING,
      check: status === OUTBOUND_STATUS.WAITING_SHIPPING,
      view: true
    },
    logistics: {
      ship: status === OUTBOUND_STATUS.COMPLETED,
      view: true
    },
    operator: {
      create: true,
      view: true
    }
  }

  return permissionMatrix[userRole]?.[action] || false
}

// 获取出库单当前可执行的操作
export function getOutboundActions(outbound, userRole) {
  if (!outbound) return []

  const actions = []
  
  // 审核操作
  if (checkOutboundPermission(outbound, 'approve', userRole)) {
    actions.push({
      key: 'approve',
      text: '审核',
      type: 'primary'
    })
  }
  
  // 拣货操作
  if (checkOutboundPermission(outbound, 'pick', userRole)) {
    actions.push({
      key: 'pick',
      text: '开始拣货',
      type: 'primary'
    })
  }
  
  // 验货操作
  if (checkOutboundPermission(outbound, 'check', userRole)) {
    actions.push({
      key: 'check',
      text: '验货确认',
      type: 'primary'
    })
  }
  
  // 发货操作
  if (checkOutboundPermission(outbound, 'ship', userRole)) {
    actions.push({
      key: 'ship',
      text: '发货确认',
      type: 'primary'
    })
  }
  
  // 取消操作
  if (checkOutboundPermission(outbound, 'cancel', userRole)) {
    actions.push({
      key: 'cancel',
      text: '取消',
      type: 'text',
      danger: true
    })
  }
  
  return actions
}

// 获取出库单状态时间线
export function getOutboundTimeline(outbound) {
  if (!outbound) return []

  const timeline = []
  
  // 创建时间
  if (outbound.createTime) {
    timeline.push({
      time: outbound.createTime,
      title: '创建出库单',
      content: `创建人：${outbound.creator?.name || '-'}`
    })
  }
  
  // 审核时间
  if (outbound.approveTime) {
    timeline.push({
      time: outbound.approveTime,
      title: '审核通过',
      content: `审核人：${outbound.approver?.name || '-'}`
    })
  }
  
  // 拣货时间
  if (outbound.pickTime) {
    timeline.push({
      time: outbound.pickTime,
      title: '开始拣货',
      content: `拣货人：${outbound.picker?.name || '-'}`
    })
  }
  
  // 验货时间
  if (outbound.checkTime) {
    timeline.push({
      time: outbound.checkTime,
      title: '验货完成',
      content: `验货人：${outbound.checker?.name || '-'}`
    })
  }
  
  // 发货时间
  if (outbound.shipTime) {
    timeline.push({
      time: outbound.shipTime,
      title: '发货完成',
      content: `发货人：${outbound.shipper?.name || '-'}${outbound.trackingNumber ? `，物流单号：${outbound.trackingNumber}` : ''}`
    })
  }
  
  // 完成时间
  if (outbound.completeTime) {
    timeline.push({
      time: outbound.completeTime,
      title: '出库完成',
      content: '出库流程已完成'
    })
  }
  
  // 取消时间
  if (outbound.cancelTime) {
    timeline.push({
      time: outbound.cancelTime,
      title: '出库取消',
      content: outbound.cancelReason ? `取消原因：${outbound.cancelReason}` : '出库单已取消'
    })
  }
  
  return timeline.sort((a, b) => new Date(a.time) - new Date(b.time))
}

// 计算出库单处理时长
export function calculateOutboundDuration(outbound) {
  if (!outbound) return null
  
  const start = outbound.createTime ? new Date(outbound.createTime) : null
  let end = null
  
  if (outbound.status === OUTBOUND_STATUS.COMPLETED) {
    end = outbound.shipTime ? new Date(outbound.shipTime) : null
  } else if (outbound.status === OUTBOUND_STATUS.CANCELLED) {
    end = outbound.cancelTime ? new Date(outbound.cancelTime) : null
  }
  
  if (!start || !end) return null
  
  const duration = end.getTime() - start.getTime()
  const hours = Math.floor(duration / (1000 * 60 * 60))
  const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
  
  return {
    hours,
    minutes,
    text: `${hours}小时${minutes}分钟`
  }
}

// 格式化出库单金额
export function formatOutboundAmount(amount) {
  if (typeof amount !== 'number') return '0.00'
  return amount.toFixed(2)
}

// 计算出库单商品总数
export function calculateOutboundTotal(items) {
  if (!Array.isArray(items)) return { quantity: 0, amount: 0 }
  
  return items.reduce((total, item) => ({
    quantity: total.quantity + (item.quantity || 0),
    amount: total.amount + ((item.price || 0) * (item.quantity || 0))
  }), { quantity: 0, amount: 0 })
}

// 验证出库单数据
export function validateOutboundData(data) {
  const errors = []
  
  // 验证客户信息
  if (!data.customerId) errors.push('客户信息不能为空')
  if (!data.customerContact) errors.push('联系人不能为空')
  if (!data.customerPhone) errors.push('联系电话不能为空')
  if (!data.customerAddress) errors.push('收货地址不能为空')
  
  // 验证商品信息
  if (!Array.isArray(data.items) || data.items.length === 0) {
    errors.push('出库商品不能为空')
  } else {
    data.items.forEach((item, index) => {
      if (!item.sku) errors.push(`第${index + 1}个商品的SKU不能为空`)
      if (!item.quantity || item.quantity <= 0) errors.push(`第${index + 1}个商品的数量必须大于0`)
    })
  }
  
  return {
    valid: errors.length === 0,
    errors
  }
} 